<template>
  <div class="home page-container">
    <!-- 导航栏 -->
    <van-nav-bar class="custom-nav" fixed placeholder>
      <template #left>
        <van-icon name="menu-o" size="24" @click="handleMenu" />
      </template>
      <template #title>
        <van-tabs 
          v-model:active="activeTab" 
          swipeable 
          animated 
          color="#fe2c55" 
          title-inactive-color="#666"
          title-active-color="#333" 
          line-height="2px" 
          @change="handleTabChange"
        >
          <van-tab v-for="tab in tabs" :key="tab.key" :title="tab.title" />
        </van-tabs>
      </template>
      <template #right>
        <van-icon name="search" size="24" @click="goToSearch" />
      </template>
    </van-nav-bar>

    <!-- 内容区域 -->
    <div class="content-container" ref="scrollContainerRef" @scroll="onScroll">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
        <template v-if="list.length">
          <Waterfall 
            :list="list" 
            :breakpoints="{
              2000: { rowPerView: 2 },
              1200: { rowPerView: 2 },
              800: { rowPerView: 2 },
              0: { rowPerView: 2 }
            }" 
            :gutter="4"
            :hasAroundGutter="true"
            ref="waterfallRef" 
            class="waterfall-container"
            :key="refreshKey" 
            align="center"
          >
            <template #default="{ item }">
              <activity-card 
                :activity="item"
                @click="goToDetail(item.id)"
              >
                <template #img>
                  <LazyImg 
                    :url="item.cover" 
                    v-if="item.cover" 
                    class="activity-image"
                  />
                </template>
              </activity-card>
            </template>
          </Waterfall>
        </template>
        
        <!-- 空状态 -->
        <van-empty v-else-if="!loading" description="暂无活动" />
        
        <!-- 底部状态 -->
        <div class="loading-status">
          <van-loading v-if="loading" size="24px">加载中...</van-loading>
          <span v-else-if="finished" class="no-more">没有更多了</span>
        </div>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { Waterfall, LazyImg } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import ActivityCard from '@/components/activity/ActivityCard.vue'
import { activityApi } from '@/api'

const router = useRouter()
const activeTab = ref(0)
const tabs = [
  { key: 'recommend', title: '推荐' },
  { key: 'following', title: '关注' },
  { key: 'nearby', title: '附近' }
]

// 数据相关
const list = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const page = ref(1)
const pageSize = 10

// 瀑布流相关
const refreshKey = ref(0)
const waterfallRef = ref(null)
const scrollContainerRef = ref<HTMLElement | null>(null)

// 检查是否触底
const isReachBottom = (el: HTMLElement): boolean => {
  const { scrollHeight, scrollTop, clientHeight } = el
  return scrollHeight - scrollTop - clientHeight < 50
}

// 滚动事件处理
const onScroll = async (e: Event) => {
  const target = e.target as HTMLElement
  if (!loading.value && !finished.value && isReachBottom(target)) {
    await fetchData()
  }
}

// 下拉刷新
const onRefresh = async () => {
  page.value = 1
  finished.value = false
  loading.value = false
  await fetchData()
  refreshing.value = false
  showToast('刷新成功')
}

// 获取活动列表数据
const formatActivityData = (item: any) => {
  return {
    ...item,
    // 统一使用 startTime 字段
    startTime: item.startTime || item.start_time,
    // 其他字段映射...
  };
};

const fetchData = async () => {
  if (loading.value || finished.value) return
  
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))

    const response = await activityApi.getActivityList({
      page: page.value,
      pageSize,
      type: tabs[activeTab.value].key
    })

    if (!response.data?.list) {
      throw new Error('返回数据格式错误')
    }

    const newActivities = response.data.list.map(formatActivityData)

    if (page.value === 1) {
      list.value = newActivities
    } else {
      list.value = [...list.value, ...newActivities]
    }

    page.value++
    finished.value = newActivities.length < pageSize
  } catch (error) {
    console.error('获取活动列表失败:', error)
    showToast('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 页面事件处理
const handleMenu = () => {
  showToast('菜单功能开发中')
}

const goToSearch = () => {
  router.push('/search')
}

const handleTabChange = () => {
  list.value = []
  page.value = 1
  finished.value = false
  loading.value = false
  fetchData()
}

const goToDetail = (id: number) => {
  router.push(`/activity/detail/${id}`)
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    fetchData()
  })
})
</script>

<style lang="scss" scoped>
.home {
  min-height: 100vh;
  background-color: #eee;
  display: flex;
  flex-direction: column;

  .custom-nav {
    :deep(.van-nav-bar__content) {
      height: 44px;
    }

    :deep(.van-nav-bar__title) {
      width: 70%;
      display: flex;
      justify-content: center;
    }

    :deep(.van-tabs) {
      width: 100%;
      height: 44px;

      .van-tabs__wrap {
        height: 100%;
      }

      .van-tabs__nav {
        background: transparent;
      }

      .van-tab {
        padding: 0 12px;
        color: #666;
        font-size: 15px;
        line-height: 44px;
      }

      .van-tab--active {
        color: #333;
        font-weight: 600;
      }

      .van-tabs__line {
        bottom: 6px;
        height: 2px;
      }
    }

    :deep(.van-icon) {
      color: #333;
    }
  }

  .content-container {
    flex: 1;
    height: calc(100vh - 44px);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    // padding: 8px 4px;
    
    &::-webkit-scrollbar {
      width: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 2px;
    }
  }

  .waterfall-container {
    min-height: 100%;
  }

  :deep(.waterfall-item) {
    break-inside: avoid;
    box-sizing: border-box;
  }

  .loading-status {
    text-align: center;
    padding: 16px 0;
    color: #999;
    font-size: 14px;
    
    .van-loading {
      margin: 0 auto;
    }

    .no-more {
      color: #999;
      font-size: 14px;
    }
  }

  .activity-image {
    width: 100%;
    border-radius: 8px;
    overflow: hidden;
  }
}
</style>
